#include "qinithandler.h"
#include <QProcess>
#include "utils.h"
#include <unistd.h>
#include <stdio.h>
#include <QDebug>
#include <sys/prctl.h>
#include <signal.h>

QInitHandler::QInitHandler(QObject* parent) : QDBusAbstractAdaptor(parent)
{

}

int QInitHandler::init(QString name, int argc, QString args, QStringList paths)
{
#ifdef QT_DEBUG
    qDebug() << name << argc << args << paths;
#endif
    QString exec_path;
    // 获得绝对路径
    if(name[0] != '/')
    {
        exec_path = execpath_avoid_loops(name, paths, false);
    }
    else
    {
        exec_path = execpath_avoid_loops(name, paths, true);
    }
    int index = exec_path.lastIndexOf('/');
    QString cwd = exec_path.mid(0, index);
    qDebug() << cwd;
    QByteArray executable = exec_path.toLocal8Bit();
    pid_t f = fork();

    // 构建参数数组
    char* argv[100];
    QByteArray name_array = exec_path.mid(index+1).toLatin1();
    argv[0] = name_array.data();
    QStringList list = args.split(" ");
    QList<QByteArray> array;
    for(int i=0; i<list.size(); i++)
    {
        QByteArray args_array = list.at(i).toLatin1();
        argv[i+1] = args_array.data();
        array.append(args_array);
    }
    argv[argc+1] = NULL;
    switch(f)
    {
    case -1:
        qDebug() << "qinithandler:init " << "fork fail";
        return -1;
    case 0:
        // child
        chdir(cwd.toStdString().c_str());
        prctl(PR_SET_PDEATHSIG,SIGKILL); // 父进程退出子进程也退出
        if (!executable.isEmpty()) {
            execvp(executable.constData(), argv);
        }
        qDebug() << executable;
        break;
    default:
        // parent
        break;
    }
    return 0;
}
